package com.talent.jiwen_teacher.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.abc.live.ABCLiveUIHelp;
import com.abc.live.OrderBean;
import com.abc.live.widget.common.ABCLiveControllerView;
import com.abcpen.core.define.ABCConstants;
import com.abcpen.open.api.model.RoomMo;
import com.talent.jiwen_teacher.R;
import com.talent.jiwen_teacher.chatlive.InteractiveActivity;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.OrderListResult;
import com.talent.jiwen_teacher.http.result.OrderResult;
import com.talent.jiwen_teacher.ui.widgets.CourseInfoNewView;
import com.talent.jiwen_teacher.util.MyToast;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;

public class CourseWaitAdapter extends RecyclerView.Adapter<CourseWaitAdapter.CourseWaitViewHolder> {

    private Context context;
    private List<OrderListResult.Order> dataList;
    private List<CourseWaitViewHolder> holderList = new ArrayList<>();

    private String finalTime;


    public CourseWaitAdapter(Context context, List<OrderListResult.Order> dataList) {
        this.context = context;
        this.dataList = dataList;

        finalTime = context.getString(R.string.final_time);
    }

    @Override
    public CourseWaitViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//        View view = LayoutInflater.from(context).inflate(R.layout.item_wait_course, parent , false);
        View view = LayoutInflater.from(context).inflate(R.layout.item_wait_course_new, parent, false);

        return new CourseWaitViewHolder(view);
    }

    @Override
    public void onBindViewHolder(CourseWaitViewHolder holder, final int position) {
        holder.setDataPosition(position);
        if (!(holderList.contains(holder))) {
            holderList.add(holder);
        }

        final OrderListResult.Order data = dataList.get(position);

        holder.courseInfoView.bindData(data);

        holder.timeTv.setText(data.getChangeTime());

        if (data.getAnswerType() == 1) {
            //即时
//            holder.enterTv.setBackgroundColor(ContextCompat.getColor(context , R.color.common_app_color));
            holder.enterTv.setBackgroundResource(R.drawable.bg_corner_green1);
            holder.enterTv.setText(context.getString(R.string.enter_course));
            holder.enterTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startClass(data.getOrderId(), data,position);
                }
            });
        } else {
            //预约
            judgeEnterTv(holder.enterTv, holder.timeTv, position);
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    /**
     * 判断预约单操作状态
     *
     * @param enterTv
     * @param timeTv
     * @param position
     */
    private void judgeEnterTv(TextView enterTv, TextView timeTv, final int position) {

        final OrderListResult.Order order = dataList.get(position);

        if (order.getOrderStatus() == 5) {
//            enterTv.setBackgroundColor(ContextCompat.getColor(context , R.color.common_app_color));
            enterTv.setBackgroundResource(R.drawable.bg_corner_green1);
            enterTv.setText("继续课程");
            enterTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    startClass(order.getOrderId());
                    ABCLiveControllerView.isHiddenController = false;
                    goLive(order.getOrderId(), order);
                }
            });
        } else {
            if (timeTv.getText().toString().equals(finalTime)) {
                enterTv.setBackgroundResource(R.drawable.bg_corner_green1);
//                enterTv.setBackgroundColor(ContextCompat.getColor(context , R.color.common_app_color));
                enterTv.setText(context.getString(R.string.enter_course));
                enterTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startClass(order.getOrderId(), order,position);
                    }
                });

            } else {
                enterTv.setBackgroundResource(R.drawable.bg_corner_baba);
//                enterTv.setBackgroundColor(ContextCompat.getColor(context , R.color.color_BABABA));
                enterTv.setText("取消订单");
                enterTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        teacherCancelOrder(order.getOrderId(), position);
                    }
                });
            }
        }
    }

    /**
     * 只刷新相关数据
     */
    public void notifyData() {
        if (dataList.size() > holderList.size() || dataList.size() == holderList.size()) {
            for (int i = 0; i < holderList.size(); i++) {
                holderList.get(i).timeTv.setText(dataList.get(holderList.get(i).position).getChangeTime());

                if (!Validators.isEmpty(dataList.get(holderList.get(i).position).getChangeTime())) {
                    if (dataList.get(holderList.get(i).position).getChangeTime().equals(finalTime)) {
                        judgeEnterTv(holderList.get(i).enterTv, holderList.get(i).timeTv, holderList.get(i).position);
                    }
                }
            }
        } else {
            holderList.clear();
            notifyDataSetChanged();
        }
    }

    class CourseWaitViewHolder extends RecyclerView.ViewHolder {

        //        CourseInfoView courseInfoView ;
        CourseInfoNewView courseInfoView;
        TextView timeTv;
        TextView enterTv;

        private int position;

        public void setDataPosition(int position) {
            this.position = position;
        }

        public CourseWaitViewHolder(View itemView) {
            super(itemView);

            courseInfoView = itemView.findViewById(R.id.courseInfoView);
            timeTv = itemView.findViewById(R.id.timeTv);
            enterTv = itemView.findViewById(R.id.enterTv);
        }
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    private void teacherCancelOrder(String orderId, final int postion) {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", SPUtil.getUserId());
        map.put("orderId", orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().teacherCancelOrder(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber(context) {
            @Override
            protected void _onNext(Object o) {
                MyToast.show(context, "取消成功");
                dataList.remove(postion);
                notifyDataSetChanged();
            }

            @Override
            protected void _onError(String message) {
                MyToast.show(context, message);
            }
        }, true);
    }


    int aginCount = 0;

    /**
     * 老师开始上课
     */
    private void startClass(final String orderId, final OrderListResult.Order order, final int position) {

        Map<String, String> map = new HashMap<>();
        map.put("teacherId", SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId", orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().teacherStartClass(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderResult>(context) {
            @Override
            protected void _onNext(OrderResult orderResult) {
                goLive(orderId, order);
            }

            @Override
            protected void _onError(String message) {
                if(!Validators.isEmpty(message)){
                    if(message.equals("该订单已超时")){
                        dataList.remove(position);
                        notifyDataSetChanged();
                    }else{
                        aginCount++;
                        if (aginCount < 5) {
                            startClass(orderId, order,position);
                        } else {
                            aginCount = 0;
                            MyToast.show(context, message);
                        }
                    }
                }
            }
        }, true);
    }


    public void goLive(String roomId, OrderListResult.Order order) {
        String rid = roomId;
        int liveType = 2;
        ABCLiveUIHelp uiHelp = ABCLiveUIHelp.init()
                .setUserID(SPUtil.getBSUId())
                .setUserName(SPUtil.getUserName())
                .setIsManager(false)
                .setDefaultOpenCamera(false)
                .setDefaultOpenMic(true);

        RoomMo roomMo = new RoomMo();
        roomMo.room_id = rid;
        roomMo.name = rid;
        roomMo.live_type = liveType;
//        startLiveActivity(uiHelp, roomMo,order);
        ABCLiveUIHelp abcLiveUIHelp = null;
        if (!SPUtil.booleanDataOut(SPConstant.IS_FIRST_GUIDE)) {
            abcLiveUIHelp = uiHelp.setIsShowGuide(true);
            SPUtil.booleanDataIn(SPConstant.IS_FIRST_GUIDE, true);
        } else {
            abcLiveUIHelp = uiHelp.setIsShowGuide(false);
        }
        abcLiveUIHelp.setIsManager(false);
        roomMo.isRecord = 1;//isRecording ? 1 : 2
        abcLiveUIHelp.setUserIconDefault(R.drawable.abc_default_icon);
        abcLiveUIHelp.setUserAvatarUrl(SPUtil.getUserHeadImg());
//        abcLiveUIHelp.setEndTime(System.currentTimeMillis() + 45 * 1000);
        abcLiveUIHelp.setStartTime(System.currentTimeMillis() + 10 * 1000);
        abcLiveUIHelp.setRoleType(ABCConstants.HOST_TYPE);
        abcLiveUIHelp.startInteractiveLiveActivity(context, roomMo, InteractiveActivity.class, new OrderBean(order.getQuestionIntroduction(), order.getQuestionImages(), order.getOrderType()));
    }

}
